<template>
  <div class="companyUser">
    <el-card shadow="hover" class="pcOnly" style="margin-bottom: 20px">
      <el-form :inline="true" label-width="80">
        <el-form-item >
          <el-button type="primary" @click="addUserDialogOpen">添加员工</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="hover" class="pcOnly" style="flex: 1" body-style="display:flex;height:100%;overflow:hidden;justify-content: center">
      <div style="overflow: auto;justify-content: center">
        <el-table :data="companyUserList" border fit v-loading="showLoading">
            <el-table-column :prop="item.dataKey" :label="item.title" :formatter="handleFormatter" :width="item.width" resizable show-overflow-tooltip v-for="item in tableHeader"/>
            <el-table-column fixed="right" label="操作" width="180">
              <template #default="scope">
                <el-popconfirm
                    width="220"
                    confirm-button-text="确定"
                    cancel-button-text="取消"
                    :icon="RemoveFilled"
                    icon-color="red"
                    title="确定要删除该员工嘛?"
                    @confirm="handleDeleteCompanyUser(scope.$index, scope.row)"
                    v-if="canDelete(scope.row)"
                >
                  <template #reference>
                    <el-button link type="primary" size="small">删除</el-button>
                  </template>
                </el-popconfirm>
                <el-button v-if="canSetAdmin(scope.row)" link type="primary" size="small" @click="handleSetCompanyAdmin(scope.$index, scope.row)">设置管理员</el-button>
                <el-button v-if="canRemoveAdmin(scope.row)" link type="primary" size="small" @click="handleRemoveCompanyAdmin(scope.$index, scope.row)">移除管理员</el-button>
              </template>
            </el-table-column>
          </el-table>
      </div>
    </el-card>
    <el-button v-if="canAddUser" class="mobileOnly" type="success" @click="addUserDialogOpen">添加员工</el-button>
    <el-dialog
        draggable title="添加新员工" :model-value="addUserDialogVisible" @closed="addUserDialogClose" width="400">
      <el-form @submit="handleAddCompanyUser">
        <el-form-item label="账号">
          <el-input
              v-model="newUserInputData"
              placeholder="请输入用户名、邮箱或者手机号"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" native-type="submit">确认</el-button>
          <el-button @click="addUserDialogClose">关闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  useAddCompanyUser,
  useDeleteCompanyUser,
  useGetCompanyId,
  useGetCompanyUserListRef,
  useGetCompanyUserRoleRef,
  useRemoveCompanyUserAdmin,
  useSetCompanyUserAdmin
} from "@/composition/billSys/useAccount.js";
import {getCurrentCompanyName} from "@/composition/useRouterLink.js";
import {RemoveFilled} from "@element-plus/icons-vue";
import {CompanyRole, CompanyRoleName} from "@/roleTypes/company.js";
import {elTip} from "@/utils/index.js";

onMounted(() => {
  console.log('companyUser Page onMounted');
});

// 公司id
const companyId = useGetCompanyId(getCurrentCompanyName());
// 公司员工列表
const companyUserList = useGetCompanyUserListRef(companyId);
// 自己的职位
const myRole = useGetCompanyUserRoleRef(companyId, localStorage['id']);
// 判断该用户我是否能删除
const canDelete = (row) => {
  return [CompanyRole.ADMIN, CompanyRole.CREATOR].includes(myRole.value) && row.role !== CompanyRole.CREATOR;
};
// 判断该用户我是否能设置管理员
const canSetAdmin = (row) => {
  return [CompanyRole.ADMIN, CompanyRole.CREATOR].includes(myRole.value) && ![CompanyRole.ADMIN, CompanyRole.CREATOR].includes(row.role);
};
// 判断该用户我是否能移除管理员
const canRemoveAdmin = (row) => {
  return [CompanyRole.ADMIN, CompanyRole.CREATOR].includes(myRole.value) && row.role === CompanyRole.ADMIN;
};
// 判断我是否能够添加人员
const canAddUser = () => {
  return [CompanyRole.ADMIN, CompanyRole.CREATOR].includes(myRole.value);
};

// 表单
const showLoading = ref(false);
// 定义table 表头
const tableHeader = [
  {
    dataKey: `role`,
    title: `职位`,
    width: 80
  },
  {
    dataKey: `email`,
    title: `邮箱`,
    width: 200
  },
  {
    dataKey: `手机号`,
    title: `手机号`,
    width: 120
  },
  {
    dataKey: `username`,
    title: `名称`,
    width: 120
  }
];

// 格式化用户职位名称
const handleFormatter = (row, col, value, index) => {
  if (col.property === 'role') {
    return CompanyRoleName[value];
  }
  return value;
};

// 删除公司员工
const handleDeleteCompanyUser = async (index, rowData) => {
  let userId = rowData.userId;
  showLoading.value = true;
  try {
    // 删除公司员工
    await useDeleteCompanyUser(companyId, userId);
  } catch (e) {
    console.log(e);
  }
  showLoading.value = false;
};


// ------------------------------------------------------------- 2 ----------------------------------------------------
// 添加新员工弹窗
const addUserDialogVisible = ref(false);
// 添加新员工的输入框的数据
const newUserInputData = ref('');
// 弹窗关闭
const addUserDialogClose = () => {
  addUserDialogVisible.value = false;
  newUserInputData.value = '';
};
// 弹窗打开
const addUserDialogOpen = () => {
  addUserDialogVisible.value = true;
};
// 添加公司员工
const handleAddCompanyUser = async (e) => {
  // 防止网页刷新
  e.preventDefault();
  if(newUserInputData.value === ''){
    elTip('请输入员工账号', 'error');
    return;
  }
  showLoading.value = true;
  try {
    // 添加公司员工
    await useAddCompanyUser(companyId, newUserInputData.value);
  } catch (e) {
    console.log(e);
  }
  showLoading.value = false;
  addUserDialogClose();
};

// 设置管理员
const handleSetCompanyAdmin = async (index, rowData) => {
  let userId = rowData.userId;
  showLoading.value = true;
  try {
    // 设置管理员
    await useSetCompanyUserAdmin(companyId, userId);
  } catch (e) {
    console.log(e);
  }
  showLoading.value = false;
};

// 删除管理员
const handleRemoveCompanyAdmin = async (index, rowData) => {
  let userId = rowData.userId;
  showLoading.value = true;
  try {
    // 删除管理员
    await useRemoveCompanyUserAdmin(companyId, userId);
  } catch (e) {
    console.log(e);
  }
  showLoading.value = false;
};
</script>

<style scoped lang="scss">
.companyUser {
  width: 100%;
  height: calc(100% - 50px - 33px);
  padding: 10px;
  background-color: $bg-color-gray;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

</style>
